<template>
  <div class="addr">
    <group label-width="4.5em"
           label-margin-right="2em"
           label-align="left"
           gutter='0'>
      <cell title="地址选择"
            value-align="left"
            :value="addr"
            is-link
            @click.native="showAddress = true"></cell>
      <x-address title="地址选择"
                 style="display:none"
                 raw-value
                 :list="addressData"
                 value-text-align="left"
                 class="addr"
                 ref="address"
                 @on-hide="chooseAddr"
                 :show.sync="showAddress"></x-address>
      <x-textarea title="详细地址"
                  placeholder="请填写详细地址"
                  :rows="3"
                  v-model="detail"
                  @on-change='textChange'></x-textarea>
    </group>
    <div class="btn flex"
         :class="{'active':active}"
         @click="submit">
      确定
    </div>
    <toast v-model="toastshow"
           type="text"
           width="200px"
           position="moddle">{{mesg}}~</toast>
  </div>
</template>
<script>
import { Group, Toast, XAddress, ChinaAddressV4Data, XTextarea, Cell } from 'vux'
import * as API from '../../api'
import { mapGetters, mapActions } from 'vuex'

export default {
  components: {
    Group, Toast, XAddress, ChinaAddressV4Data, XTextarea, Cell
  },
  data () {
    return {
      active: false,
      toastshow: false,
      addr: '',
      addressData: ChinaAddressV4Data,
      detail: '',
      mesg: '',
      showAddress: false
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  created () {
    this.$http.get(API.user, {
      params: {
        openId: this.userInfo.openId
      } }).then(res => {
      this.addr = res.data.province + ' ' + res.data.city + ' ' + res.data.area
      this.detail = res.data.address
      this.initUser(res.data)
    }).catch(err => {
      console.log(err)
    })
  },
  methods: {
    ...mapActions(['initUser']),
    submit () {
      this.toastshow = true
      if (this.detail === '') {
        this.mesg = '请填写详细地址'
      } else {
        this.toastshow = false
        this.$http.post(API.addr, {
          openId: this.userInfo.openId,
          city: this.addr,
          address: this.detail
        }).then(res => {
          this.$router.push('/my')
        }).catch(err => {
          console.log(err)
        })
      }
    },
    chooseAddr () {
      this.addr = this.$refs.address.nameValue
    },
    textChange () {
      this.active = true
    }
  }

}
</script>
<style lang="scss" scoped>
@import "../../assets/style/index.scss";
</style>
